﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Text.RegularExpressions;
using System.Text;
using System.Globalization;
using System.Web.Caching;
using Aandelendelen.Obs;
using Aandelendelen.Caching;

namespace Aandelendelen.Stocks
{
	public class StockCollection : Dictionary<int, Stock>, ICacheable
	{
		public static string CacheName = "data_stocks"; 

		public StockCollection()
			: base(32)
		{
			this.InitCacheKey();
			this.Populate();
		}
		
		private void Populate()
		{
			string url = "http://www.belegger.nl/koersen-AEX.index";
			string response = WebReader.ReadUrl(url);
			this.ParseResponse(response, "AEX");

			url = "http://www.belegger.nl/koersen-AMX.index";
			response = WebReader.ReadUrl(url);
			this.ParseResponse(response, "AMX");
			/*
			url = "http://www.belegger.nl/koersen-ASCX.index";
			response = WebReader.ReadUrl(url);
			this.ParseResponse(response, "ASCX");
			 */
		}

		private void ParseResponse(string response, string market)
		{
			Regex regEx = new Regex("<div source=\"lightstreamer\" item=\"(?'item'\\d{1,3})\" field=\"(?'field'[^\"]*)\"[^>]*>(?'value'[^<]*)</div>", RegexOptions.Compiled | RegexOptions.Singleline);

			StockMatchHelper matchHelper = new StockMatchHelper();
			DateTime dt = DateTime.Now;
			MatchCollection matches = regEx.Matches(response);
			DateTime dt2 = DateTime.Now;
			TimeSpan ts = dt2 - dt;

			foreach (Match match in matches)
			{
				Group itemGroup = match.Groups["item"];
				Group fieldGroup = match.Groups["field"];
				Group valueGroup = match.Groups["value"];

				matchHelper.Add(itemGroup.Value, fieldGroup.Value, valueGroup.Value);
			}

			matchHelper.PopulateStocks(this, market);
		}

		public static StockCollection GetInstance()
		{
			return DataCache.GetCacheableObject<StockCollection>(CacheName);
		}

		public static StockCollection GetInstance(string cacheKey)
		{
			return DataCache.GetCacheableObject<StockCollection>(cacheKey);
		}

		#region ICacheable
		public CacheKey CacheKey { get; set; }

		public void CacheThis(string cacheKey)
		{
			this.CacheKey.CacheThis(cacheKey);
		}

		public void InitCacheKey()
		{
			CacheKey = new CacheKey()
			{
				SecondsBeforeInvalidate = 300,
				ObjectToCache = this
			};
		}
		#endregion
	}
}